package com.joseph.websocket.nio;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.internal.shaded.org.jctools.queues.MpscChunkedArrayQueue;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer {

    static ServerSocket serverSocket;
    static {
        try {
            /**
             * 1、int socket(int af, int type, int protocol); 创建一个socket
             * 2、bind地址 int bind(int sock, struct sockaddr *addr, socklen_t addrlen);
             * 3、开启监听 int listen(int sock, int backlog);
             */
            serverSocket = new ServerSocket(8888, 128); // 底层已经调用了 bind listen
            System.out.println("server started!!！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        new BIOServer().init();
    }

    public void init() {
        Socket accept = null;
        while (true) {
            try {
                accept = serverSocket.accept(); //阻塞 int accept(int sock, struct sockaddr *addr, socklen_t *addrlen);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("client connected!" + accept.getRemoteSocketAddress());
            try {
                Socket finalAccept = accept;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            handerSocket(finalAccept);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void handerSocket(Socket accept) throws IOException  {
        while (true) {
            InputStream inputStream = accept.getInputStream();
            OutputStream outputStream = accept.getOutputStream();
            byte[] revData = new byte[100];
            while (inputStream.read(revData) != -1) {
                System.out.println("revc client data ：" + new String(revData) + "from :" + accept.getRemoteSocketAddress()) ;
                break;
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            outputStream.write(revData);
            outputStream.flush();
        }
    }
}
